import { Product } from "../models/product";
import productReducer from "../store/reducers/product.reducer";

export interface CartItem extends Product {
  count: number
}

export const addCart = (item: Product, next: ()=>void)=>{
  let cart:CartItem[] = []

  if(localStorage.getItem('cart')) {
    cart = JSON.parse(localStorage.getItem('cart')!)
  }
  cart.push({
    ...item,
    count: 1
  })
  
  cart = Array.from(new Set(cart.map(item=>item._id))).map(item=>{
    return cart.find(cartItem=>cartItem._id===item)
  }) as CartItem[]

  localStorage.setItem('cart', JSON.stringify(cart))

  next()
}

export const getCart = () => {
  let cart:CartItem[] = []
  if(localStorage.getItem('cart')) {
    cart = JSON.parse(localStorage.getItem('cart')!)
  }
  return cart
}

export const updateCartItem = (productId:string,count:number) => {
  let cart:CartItem[] = []

  if(localStorage.getItem('cart')) {
    cart = JSON.parse(localStorage.getItem('cart')!)
  }

  cart.forEach((item, index)=>{
    if(item._id === productId) {
      cart[index].count = count
    }
  })

  localStorage.setItem('cart', JSON.stringify(cart))

  return cart
}

export const deleteCartItem = (productId:string) => {
  let cart:CartItem[] = []

  if(localStorage.getItem('cart')) {
    cart = JSON.parse(localStorage.getItem('cart')!)
  }

  cart.forEach((item, index)=>{
    if(item._id === productId) {
      cart.splice(index, 1)
    }
  })

  localStorage.setItem('cart', JSON.stringify(cart))

  return cart
}

export const itemCount = () => {
  let cart:CartItem[] = []
  if(localStorage.getItem('cart')) {
    cart = JSON.parse(localStorage.getItem('cart')!)
    return cart.length
  }
  return 0
}